/* eslint-disable no-unneeded-ternary */
import * as api from './api';
import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import {PAGE} from '../constants';
import {conventTableCondition} from '../utils';
import {newOrUpdateOrderValidator, financeValidator, approveValidator, approveRejectValidator} from './validator';
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = message => ({
    type: GET_INIT_FAIL,
    message
});

//获取初始化数据和权限

export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk)
            dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else
            dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};
/*==============================查询列表================================= */
export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';

export const getListBegin = () => ({
    type: GET_LIST_BEGIN,
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition,
});
export const getListFail = () => ({
    type: GET_LIST_FAIL
});

//获取列表
export const getList = condition => dispatch => {
    if(!condition)
        return;
    const queryCondition = conventTableCondition(condition);
    const {dealerCode, dealerName, issueCountryChineseName, ...props} = queryCondition;
    dispatch(getListBegin());
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
    });
};
//按钮搜索
export const querySearch = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    dispatch(getList(condition));
};
//分页排序搜索
export const tableSearch = page => (dispatch, getState) => {
    const query = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

/*==============================查询action================================= */
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
/*==============================重置查询条件================================= */
export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL
});

/*==============================新增修改action================================= */
export const onSubmit = data => () => {
    //增加判断必填字段
    if(!newOrUpdateOrderValidator(data))
        return Promise.resolve({success: false});
    return data.id ? api.modifyOrder(data.id, {
        rowVersion: data.rowVersion,
        lcCode: data.lcCode,
        issueCountryId: data.issueCountryId,
        issueBank: data.issueBank,
        issuePrice: data.issuePrice,
        currency: data.currency,
        lcPayMentDays: data.lcPayMentDays,
        issueDate: data.issueDate,
        lastLoadDate: data.lastLoadDate,
        shippingPortId: data.shippingPortId,
        destinationPort: data.destinationPort,
        isAllowBatch: data.isAllowBatch === 1 ? true : false,
        isAllowTransfer: data.isAllowTransfer === 1 ? true : false,
        quantity: data.quantity,
        dateOfExpiry: data.dateOfExpiry,
        placeOfExpiry: data.placeOfExpiry,
        lcOfficialDraftType: data.lcOfficialDraftType,
        commodityDescription: data.commodityDescription,
        remark: data.remark,
        attachments: data.attachments
    }).then(res => ({success: res.ok})) : api.newOrder({
        brandId: data.brandId,
        dealerId: data.dealerId,
        lcCode: data.lcCode,
        issueCountryId: data.issueCountryId,
        issueBank: data.issueBank,
        issuePrice: data.issuePrice,
        currency: data.currency,
        lcPayMentDays: data.lcPayMentDays,
        issueDate: data.issueDate,
        lastLoadDate: data.lastLoadDate,
        shippingPortId: data.shippingPortId,
        destinationPort: data.destinationPort,
        isAllowBatch: data.isAllowBatch === 1 ? true : false,
        isAllowTransfer: data.isAllowTransfer === 1 ? true : false,
        quantity: data.quantity,
        dateOfExpiry: data.dateOfExpiry,
        placeOfExpiry: data.placeOfExpiry,
        lcOfficialDraftType: data.lcOfficialDraftType,
        lcKind: data.lcKind,
        commodityDescription: data.commodityDescription,
        remark: data.remark,
        attachments: data.attachments
    }).then(res => ({success: res.ok}));
};

/*==============================大区审核action================================= */
export const onSubmitApprovePass = data => () => {
    //增加判断必填字段
    if(!approveValidator(data))
        return Promise.resolve({success: false});
    return api.approvePass(data.id, {
        rowVersion: data.rowVersion,
        lastLoadDate: data.lastLoadDate,
        remark: data.remark,
        approveComment: data.approveComment,
        issuePriceIsApprove: data.issuePriceIsApprove,
        shippingPortIsApprove: data.shippingPortIsApprove,
        destinationPortIsApprove: data.destinationPortIsApprove,
        lastLoadDateIsApprove: data.lastLoadDateIsApprove,
        dateOfExpiryIsApprove: data.dateOfExpiryIsApprove,
        placeOfExpiryIsApprove: data.placeOfExpiryIsApprove,
        lcPayMentDaysMarketDepartmentIsApprove: data.lcPayMentDaysMarketDepartmentIsApprove,
        commodityDescriptionIsApprove: data.commodityDescriptionIsApprove,
    }).then(res => ({success: res.ok}));
};
export const onSubmitApproveReject = data => () => {
    //增加判断必填字段
    if(!approveRejectValidator(data))
        return Promise.resolve({success: false});
    return api.approveReject(data.id, {
        rowVersion: data.rowVersion,
        lastLoadDate: data.lastLoadDate,
        remark: data.remark,
        approveComment: data.approveComment,
        issuePriceIsApprove: data.issuePriceIsApprove,
        shippingPortIsApprove: data.shippingPortIsApprove,
        destinationPortIsApprove: data.destinationPortIsApprove,
        lastLoadDateIsApprove: data.lastLoadDateIsApprove,
        dateOfExpiryIsApprove: data.dateOfExpiryIsApprove,
        placeOfExpiryIsApprove: data.placeOfExpiryIsApprove,
        lcPayMentDaysMarketDepartmentIsApprove: data.lcPayMentDaysMarketDepartmentIsApprove,
        commodityDescriptionIsApprove: data.commodityDescriptionIsApprove,
    }).then(res => ({success: res.ok}));
};
/*==============================财务审核action================================= */
export const onSubmitFinancePass = data => () => {
    //增加判断必填字段
    if(!financeValidator(data))
        return Promise.resolve({success: false});
    return api.financePass(data.id, {
        rowVersion: data.rowVersion,
        remark: data.remark,
        approveComment: data.approveComment,
        issueBankIsApprove: data.issueBankIsApprove,
        lcKindIsApprove: data.lcKindIsApprove,
        lcPayMentDaysFinanceIsApprove: data.lcPayMentDaysFinanceIsApprove
    }).then(res => ({success: res.ok}));
};
export const onSubmitFinanceReject = data => () => {
    //增加判断必填字段
    if(!approveRejectValidator(data))
        return Promise.resolve({success: false});
    return api.financeReject(data.id, {
        rowVersion: data.rowVersion,
        remark: data.remark,
        approveComment: data.approveComment,
        issueBankIsApprove: data.issueBankIsApprove,
        lcKindIsApprove: data.lcKindIsApprove,
        lcPayMentDaysFinanceIsApprove: data.lcPayMentDaysFinanceIsApprove
    }).then(res => ({success: res.ok}));
};
/*==============================草本转正本action================================= */
export const draft = data => () => api.draftData(data.id, {
    rowVersion: data.rowVersion,
    lcCode: data.lcCode,
    issueCountryId: data.issueCountryId,
    issueBank: data.issueBank,
    issuePrice: data.issuePrice,
    currency: data.currency,
    lcPayMentDays: data.lcPayMentDays,
    issueDate: data.issueDate,
    lastLoadDate: data.lastLoadDate,
    shippingPortId: data.shippingPortId,
    destinationPort: data.destinationPort,
    isAllowBatch: data.isAllowBatch === 1 ? true : false,
    isAllowTransfer: data.isAllowTransfer === 1 ? true : false,
    quantity: data.quantity,
    dateOfExpiry: data.dateOfExpiry,
    placeOfExpiry: data.placeOfExpiry,
    remark: data.remark,
    attachments: data.attachments
}).then(res => ({success: res.ok}));

//导出
export const exportData = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    if(!condition)
        return;
    const queryCondition = conventTableCondition(condition);
    const {dealerCode, dealerName, issueCountryChineseName, pageIndex, pageSize, ...props} = queryCondition;
    return api.exportDate(props).then(res => {
        if(res.ok)
            return res.data;
    });
};

export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealerQuery = data => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});
export const SELECT_AREA_QUERY = 'SELECT_AREA_QUERY';
export const selectAreaQuery = data => ({
    type: SELECT_AREA_QUERY,
    data: {
        issueCountryId: data.id,
        issueCountryChineseName: data.chineseName,
    }
});


/*==============================查历史查询================================= */
/*==============================查询列表================================= */
export const GET_LIST_BEGIN_HISTORY = 'GET_LIST_BEGIN_HISTORY';
export const GET_LIST_SUCCESS_HISTORY = 'GET_LIST_SUCCESS_HISTORY';
export const GET_LIST_FAIL_HISTORY = 'GET_LIST_FAIL_HISTORY';

export const getListBeginHistory = () => ({
    type: GET_LIST_BEGIN_HISTORY,
});
export const getListSuccessHistory = (data, condition) => ({
    type: GET_LIST_SUCCESS_HISTORY,
    data,
    condition,
});
export const getListFailHistory = () => ({
    type: GET_LIST_FAIL_HISTORY
});

//获取列表
export const getListHistory = condition => dispatch => {
    if(!condition)
        return;
    const queryCondition = conventTableCondition(condition);
    const {dealerCode, dealerName, issueCountryChineseName, ...props} = queryCondition;
    dispatch(getListBeginHistory());
    return api.getListHistory(props).then(res => {
        if(res.ok)
            dispatch(getListSuccessHistory(res.data, condition));
        else
            dispatch(getListFailHistory());
    });
};
//按钮搜索
export const querySearchHistory = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryHistory']).toJS();
    dispatch(getListHistory(condition));
};
//分页排序搜索
export const tableSearchHistory = page => (dispatch, getState) => {
    const query = getState().getIn(['page', 'appState', 'queryBySortHistory']).toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getListHistory(condition));
};

/*==============================查询action================================= */
export const SAVE_QUERY_CONDITION_HISTORY = 'SAVE_QUERY_CONDITION_HISTORY';
export const saveQueryConditionHistory = (name, value) => ({
    type: SAVE_QUERY_CONDITION_HISTORY,
    name,
    value
});
/*==============================重置查询条件================================= */
export const RESET_QUERY_PANEL_HISTORY = 'RESET_QUERY_PANEL_HISTORY';
export const resetQueryPanelHistory = () => ({
    type: RESET_QUERY_PANEL_HISTORY
});

export const SELECT_DEALER_QUERY_HISTORY = 'SELECT_DEALER_QUERY_HISTORY';
export const selectDealerQueryHistory = data => ({
    type: SELECT_DEALER_QUERY_HISTORY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});
export const SELECT_AREA_QUERY_HISTORY = 'SELECT_AREA_QUERY_HISTORY';
export const selectAreaQueryHistory = data => ({
    type: SELECT_AREA_QUERY_HISTORY,
    data: {
        issueCountryId: data.id,
        issueCountryChineseName: data.chineseName,
    }
});
